﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProgNetComponents.Data.SqlCe;
using System.Data.SqlServerCe;

namespace Lottomat.Init
{
    class AppUpdate
    {
        private static List<Action> PreAct = new List<Action>();
        private static List<Action> PostAct = new List<Action>();

        static SqlCeDataManager manager;
        public static void Update(int lastAct)
        {
            using (manager = new SqlCeDataManager())
            {
                manager.AutoLogExceptions = true;
                if (lastAct == 0)
                {
                    CreateDB();
                }
                else
                {

                }
            }
        }
        private static void ExecuteQieries(string queries, string name)
        {
            string[] str = queries.XSplit(@"\s+GO;\s+", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
            string query;

            for (int i = 0; i < str.Length; i++)
            {
                try
                {
                    query = str[i].Trim().XReplace("GO;$", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);

                    if (query.IsNotNull())
                    {
                        manager.ExecuteNonQuery(query);
                        if (manager.LastException != null)
                            LogException(name, query, i, manager.LastException);
                    }
                }
                catch (Exception ex)
                {
                    LogException(name, str[i], i, ex);
                }
            }
        }
        private static void LogException(string name, string query, int no, Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("-------------------------------------------");
            sb.AppendLine("Błąd w skrypcie: " + name + ", polecenie numer: " + no);
            sb.AppendLine("Skrypt: " + query);
            ex.LogError(sb.ToString());
        }
        
        private static void CreateDB()
        {
            SqlCeEngine eng = new SqlCeEngine(SqlCeDataManager.GlobalConnectionString);
            try
            {
                eng.CreateDatabase();
            }
            catch { }
            ExecuteQieries(Properties.Resources.Insert_STP_TYP_LOSOWAN, "Insert_STP_TYP_LOSOWAN");
        }
    }
}
